package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.nursing.domain.*;
import com.zzyl.nursing.dto.CheckInApplyDto;
import com.zzyl.nursing.dto.CheckInConfigDto;
import com.zzyl.nursing.dto.CheckInElderDto;
import com.zzyl.nursing.dto.ElderFamilyDto;
import com.zzyl.nursing.mapper.*;
import com.zzyl.nursing.service.IElderService;
import com.zzyl.nursing.util.CodeGenerator;
import com.zzyl.nursing.util.IDCardUtils;
import com.zzyl.nursing.vo.CheckInConfigVo;
import com.zzyl.nursing.vo.CheckInDetailVo;
import com.zzyl.nursing.vo.CheckInElderVo;
import com.zzyl.nursing.vo.ElderFamilyVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.service.ICheckInService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

/**
 * 入住Service业务层处理
 * 
 * @author alexis
 * @date 2025-10-15
 */
@Service
public class CheckInServiceImpl extends ServiceImpl<CheckInMapper, CheckIn> implements ICheckInService
{
    @Autowired
    private CheckInMapper checkInMapper;
    @Autowired
    private ElderMapper elderMapper;
    @Autowired
    private BedMapper bedMapper;
    @Autowired
    private ContractMapper contractMapper;
    @Autowired
    private CheckInConfigMapper checkInConfigMapper;
    @Autowired
    private ICheckInService iCheckInService;
    @Autowired
    private IElderService iElderService;

    /**
     * 查询入住
     * 
     * @param id 入住主键
     * @return 入住
     */
    @Override
    public CheckIn selectCheckInById(Long id)
    {
        return checkInMapper.selectById(id);
    }

    /**
     * 查询入住列表
     * 
     * @param checkIn 入住
     * @return 入住
     */
    @Override
    public List<CheckIn> selectCheckInList(CheckIn checkIn)
    {
        return checkInMapper.selectCheckInList(checkIn);
    }

    /**
     * 新增入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int insertCheckIn(CheckIn checkIn)
    {
        return checkInMapper.insert(checkIn);
    }

    /**
     * 修改入住
     * 
     * @param checkIn 入住
     * @return 结果
     */
    @Override
    public int updateCheckIn(CheckIn checkIn)
    {
        return checkInMapper.updateById(checkIn);
    }

    /**
     * 批量删除入住
     * 
     * @param ids 需要删除的入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInByIds(Long[] ids)
    {
        return checkInMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除入住信息
     * 
     * @param id 入住主键
     * @return 结果
     */
    @Override
    public int deleteCheckInById(Long id)
    {
        return checkInMapper.deleteById(id);
    }

    @Override
    @Transactional
    public void apply(CheckInApplyDto checkInApplyDto) {
        //1.校验老人是否已经入住，如果已经入住直接结束  提示词：elqw BaseException elder
        checkElderCheckIn(checkInApplyDto);
        //2.更新床位状态为已入住
        Bed bed = bedMapper.selectById(checkInApplyDto.getCheckInConfigDto().getBedId());
        bed.setBedStatus(1);
        bedMapper.updateById(bed);
        //3.新增或更新老人信息
        Elder elder = insertOrUpdataElder(checkInApplyDto.getCheckInElderDto(),bed);
        //4.新增签约办理
        saveContract(checkInApplyDto,elder);
        //5.新增入住信息
        CheckIn checkIn = saveCheckIn(checkInApplyDto,elder,bed);
        //6.新增入住配置
        saveCheckInConfig(checkInApplyDto.getCheckInConfigDto(),checkIn);
    }

    private void saveCheckInConfig(CheckInConfigDto checkInConfigDto, CheckIn checkIn) {
        CheckInConfig checkInConfig = new CheckInConfig();
        BeanUtils.copyProperties(checkInConfigDto,checkInConfig);
        checkInConfig.setCheckInId(checkIn.getId());
        checkInConfigMapper.insert(checkInConfig);
    }

    private CheckIn saveCheckIn(CheckInApplyDto checkInApplyDto, Elder elder, Bed bed) {
        //checkIn
        CheckIn checkIn = new CheckIn();
        checkIn.setElderName(elder.getName());
        checkIn.setElderId(elder.getId());
        checkIn.setIdCardNo(elder.getIdCardNo());
        checkIn.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        checkIn.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        checkIn.setNursingLevelName(checkInApplyDto.getCheckInConfigDto().getNursingLevelName());
        checkIn.setBedNumber(bed.getBedNumber());
        List<ElderFamilyDto> elderFamilyDtoList =checkInApplyDto.getElderFamilyDtoList();
        checkIn.setRemark(JSON.toJSONString(elderFamilyDtoList));
        checkInMapper.insert(checkIn);
        return checkIn;
    }

    private void checkElderCheckIn(CheckInApplyDto checkInApplyDto) {
        LambdaQueryWrapper<Elder> elqw = new LambdaQueryWrapper<>();
        elqw.eq(Elder::getStatus,1);
        elqw.eq(Elder::getIdCardNo,checkInApplyDto.getCheckInElderDto().getIdCardNo());
        Elder elder = elderMapper.selectOne(elqw);
        if(ObjectUtil.isNotNull(elder)){
            throw new BaseException("老人已入住");
        }
    }

    //提示：注释
    private Elder insertOrUpdataElder(CheckInElderDto checkInElderDto, Bed bed) {
        //查询老人信息
        Elder elder = new Elder();
        BeanUtils.copyProperties(checkInElderDto,elder);
        Elder elderDB = elderMapper.selectOne(new LambdaQueryWrapper<Elder>().eq(Elder::getIdCardNo,checkInElderDto.getIdCardNo()));
        //补全elder
        elder.setBedId(bed.getId());
        elder.setBedNumber(bed.getBedNumber());
        //如果老人信息存在，更新;不存在则新增
        if(ObjectUtil.isNotNull(elderDB)){
            elder.setId(elderDB.getId());
            elderMapper.updateById(elder);
        }else{
            elderMapper.insert(elder);
        }
        return elder;
    }

    private void saveContract(CheckInApplyDto checkInApplyDto, Elder elder) {
        //提示：提示词：contract 老人信息：elder_id elder_name start_date end_date 方法：intvalue
        Contract contract = new Contract();
        BeanUtils.copyProperties(checkInApplyDto.getCheckInContractDto(), contract);
        contract.setElderId(elder.getId().intValue());
        contract.setElderName(elder.getName());
        contract.setStartDate(checkInApplyDto.getCheckInConfigDto().getStartDate());
        contract.setEndDate(checkInApplyDto.getCheckInConfigDto().getEndDate());
        if(LocalDateTime.now().isAfter(contract.getStartDate())){
            contract.setStatus(1);
        }
        contract.setContractNumber("HT"+ CodeGenerator.generateContractNumber());
        contractMapper.insert(contract);
    }

    /**
     * 入住详情
     *
     * @param id
     */
    @Override
    public CheckInDetailVo detail(Long id) {
        CheckIn checkIn = checkInMapper.selectById(id);
        if (checkIn == null) {
            return null;
        }
        Long elderId = checkIn.getElderId();
        Elder elder =  elderMapper.selectById(elderId);
        if(elder==null){
            return null;
        }
        CheckInElderVo vo1 = new CheckInElderVo();
        BeanUtils.copyProperties(elder,vo1);
        vo1.setAge(IDCardUtils.deriveAge(elder.getIdCardNo()));
        Contract contract = contractMapper.selectOne(
                new LambdaQueryWrapper<Contract>()
                        .eq(Contract::getElderId, elderId)
        );
        CheckInConfigVo vo2 = new CheckInConfigVo();
        BeanUtils.copyProperties(checkIn, vo2);
        List<ElderFamilyVo> list = JSON.parseArray(checkIn.getRemark(), ElderFamilyVo.class);
        CheckInDetailVo result = new CheckInDetailVo();
        result.setCheckInElderVo(vo1);
        result.setElderFamilyVoList(list);
        result.setCheckInConfigVo(vo2);
        result.setContract(contract);
        return result;
    }
}
